package com.sevennotes.classtable.ui.pages.studentlist

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.SoftwareKeyboardController
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.sevennotes.classtable.config.Config
import com.sevennotes.classtable.model.StudentItem
import com.sevennotes.classtable.ui.pages.components.AddItemCell
import com.sevennotes.classtable.ui.pages.components.CheckButton
import com.sevennotes.classtable.ui.pages.components.ItemCell
import com.sevennotes.classtable.ui.pages.components.SimpleComfirmDialog
import com.sevennotes.classtable.ui.pages.main_screen.StudentsListState

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun StudentsListPage(
  studentsListState: StudentsListState,
  onStuClick: (StudentItem) -> Unit,
  onStuDelete: (StudentItem) -> Unit,
  keyboard: SoftwareKeyboardController?
) {
  StudentsListPage(
    studentList = studentsListState.studentList!!.observeAsState().value ?: emptyList(),
    editable = studentsListState.editable.value,
    onStuClick = onStuClick,
    onStuDelete = onStuDelete,
    keyboard = keyboard
  )
}


@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun StudentsListPage(
  studentList: List<StudentItem>,
  editable: Boolean,
  onStuClick: (StudentItem) -> Unit,
  onStuDelete: (StudentItem) -> Unit,
  keyboard: SoftwareKeyboardController?
) {
  val stuNum = studentList.size
  val onClassStuNum = studentList.count { it.usable }
  var searchStr by remember { mutableStateOf("") }
  var onlyLessTotal by remember { mutableStateOf(false) }
  //显示usable为false的学生, 默认不显示
  var showUnUsable by remember { mutableStateOf(false) }

  Column(
    modifier = Modifier.pointerInput(Unit) {
      detectTapGestures {
        keyboard?.hide()
      }
    }
  ) {
    Spacer(modifier = Modifier.height(10.dp))
    Text(
      text = "学生总数: $stuNum 人, 在课人数：$onClassStuNum 人",
      modifier = Modifier.fillMaxWidth(),
      textAlign = TextAlign.Center
    )
    Spacer(modifier = Modifier.height(10.dp))
    LazyColumn(
      modifier = Modifier.pointerInput(Unit) {
        detectTapGestures {
          keyboard?.hide()
        }
      }
    ) {
      item {
        OutlinedTextField(
          modifier = Modifier
            .clip(RoundedCornerShape(12.dp))
            .fillMaxWidth()
            .padding(horizontal = 10.dp),
          value = searchStr,
          singleLine = true,
          onValueChange = { searchStr = it },
          placeholder = { Text("搜索") },
          trailingIcon = {
            IconButton(onClick = {searchStr = ""}) {
              Icon(imageVector = Icons.Filled.Delete, contentDescription = null)
            }
          }
        )
        ItemCell(

        ) {
          CheckButton(
            modifier = Modifier
              .weight(1f)
              .padding(horizontal = 4.dp),
            checked = onlyLessTotal,
            onCheckedChange = { onlyLessTotal = !onlyLessTotal },
            text = "课时不足"
          )
          CheckButton(
            modifier = Modifier
              .weight(1f)
              .padding(horizontal = 4.dp),
            checked = showUnUsable,
            onCheckedChange = { showUnUsable = !showUnUsable },
            text = "已停课"
          )
          Spacer(modifier = Modifier.weight(1f))
        }
        Spacer(modifier = Modifier.height(10.dp))
        Divider(color = Config.dividerColor)
      }
      studentList.forEach { studentItem ->
        item {
          var filter = if (onlyLessTotal)
            studentItem.name.contains(searchStr) && studentItem.classAmount <= 3
          else
            studentItem.name.contains(searchStr)

          filter = filter && if (showUnUsable) true else studentItem.usable
          AnimatedVisibility(visible = filter) {
            StuListCell(
              studentItem = studentItem,
              editable = editable,
              onStuClick = { onStuClick(studentItem) },
              onStuDelete = { onStuDelete(studentItem) },
            )
          }
        }
      }
    }
  }
}

@Composable
fun StuListCell(
  studentItem: StudentItem,
  editable: Boolean = false,
  onStuClick: () -> Unit = {},
  onStuDelete: () -> Unit = {},
  usable: Boolean = false,
) {
  var onDeleteDialog by remember { mutableStateOf(false) }
  if (onDeleteDialog) {
    SimpleComfirmDialog(
      text = "删除该学生会将其所有历史记录一并删除, 确认要删除吗?",
      onConfirmClick = {
        onDeleteDialog = false
        onStuDelete()
      }
    ) {
      onDeleteDialog = false
    }
  }
  Column {
    Row(
      modifier = Modifier
        .fillMaxWidth()
        .height(60.dp)
        .background(color = MaterialTheme.colors.background)
        .clickable { onStuClick() },
      verticalAlignment = Alignment.CenterVertically
    ) {
      AnimatedVisibility(editable) {
        IconButton(onClick = { onDeleteDialog = true }) {
          Icon(imageVector = Icons.Filled.Delete, contentDescription = "delete")
        }
      }
      if (!editable) {
        Spacer(modifier = Modifier.width(10.dp))
      }
      //学生姓名
      Text(
        text = studentItem.name,
        fontSize = 19.sp
      )
      if (!studentItem.usable) {
        Spacer(modifier = Modifier.width(10.dp))
        Box(modifier = Modifier
          .clip(CircleShape)
          .background(Color(249, 53, 53, 255))
          .size(25.dp),
          contentAlignment = Alignment.Center
        ) {
          Text(text = "停", color = Color.White)
        }
      }
      Spacer(modifier = Modifier.weight(1f))
      //剩余课时和积分
      Column(
        horizontalAlignment = Alignment.End,
        verticalArrangement = Arrangement.SpaceBetween
      ) {
        if (studentItem.classAmount <= 3)
          Text(text = "${studentItem.classAmount} 节", color = Config.wrong)
        else
          Text(text = "${studentItem.classAmount} 节")
        Text(text = "${studentItem.gradePoint} 分")
      }
      Spacer(modifier = Modifier.width(15.dp))
      Icon(imageVector = Icons.Filled.KeyboardArrowRight, contentDescription = "")
    }
    Divider(color = Config.dividerColor, thickness = 1.dp)
  }
}

@Preview(showBackground = true)
@Composable
fun StuListCellPrev() {
  Column {
    StuListCell(studentItem = StudentItem(name = "张三"), editable = true)
    StuListCell(studentItem = StudentItem(name = "张三", usable = true), editable = true)
    StuListCell(studentItem = StudentItem(name = "张三", usable = true))
    StuListCell(studentItem = StudentItem(name = "张三"))
  }
}

@OptIn(ExperimentalComposeUiApi::class)
@Preview(showBackground = true)
@Composable
fun ListPagePrev() {
  var stuList = listOf<StudentItem>(
    StudentItem(name = "张三"),
    StudentItem(name = "李斯"),
    StudentItem(name = "王五"),
  )
  StudentsListPage(
    studentList = stuList,
    editable = false,
    onStuClick = {},
    onStuDelete = {},
    keyboard = null
  )
}